<template>
	<div class="addProject business-workAdd">
		<div class="addForm zll-form">
			<el-form :model="addForm" :rules="rules" ref="addForm" class="demo-ruleForm">
				<el-row :gutter="40">
					<el-col :span="8">
<!--						<el-form-item class="formList" prop="name" label="客户：">-->
<!--							<el-input clearable class="input_right" v-model="addForm.customer"-->
<!--									  :disabled="type == 'see'"></el-input>-->
<!--						</el-form-item>-->
						<el-form-item class="formList" prop="name" label="客户：">
							<el-autocomplete
								v-model="addForm.customer"
								:fetch-suggestions="querySearch"
								placeholder="请输入客户名称"
								:disabled="type == 'see'"
								value-key="customer"
							>
								<template slot="default" slot-scope="{item}">
									{{ item.customer}}
								</template>
							</el-autocomplete>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="formList" prop="type" label="订单类型：">
							<el-select clearable class="input_right" v-model="addForm.orderType" :disabled="type == 'see'">
								<el-option label="内销" value="内销"></el-option>
								<el-option label="外置" value="外置"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<div class="con_p">
					<div class="mine-add" v-if="type == 'add'">
						<span class="tipss">单次下单最多10个产品</span>
						<span @click="addTable()"><i class="el-icon-circle-plus"></i></span>
						<span @click.stop="deleteTable(item,index)"><i
							class="el-icon-remove-outline"></i></span>
					</div>
				</div>
				<div class="tableList" v-if="type == 'add'">
					<table border="1">
						<tr>
							<!-- <th width="40"></th> -->
							<th>订单号</th>
							<th>品类</th>
							<th>产品名称</th>
							<th width="200">规格</th>
							<th>单件万支</th>
							<th>件数</th>
							<th>合计(万支)</th>
							<th>单价</th>
							<th>金额</th>
							<th>交货期(天)</th>
							<th>备注</th>
							<th width="60"></th>
						</tr>
						<tr v-if="tableList.length == 0" class="noData">
							<td colspan="12">暂无数据</td>
						</tr>
						<tr v-else class="add_Table" v-for="(item, index) in tableList" :key="index">
							<!-- <td width="40">
								<el-checkbox v-model="item.checked"></el-checkbox>
							</td> -->
							<td>
								<el-input v-model="item.orderNum" placeholder="" class="text_center" clearable
										  disabled></el-input>
							</td>
							<td>
								<el-select v-model="item.itemTypeId" placeholder="" class="text_center" clearable
										   :disabled="type == 'see'">
									<el-option v-for="(item,index) in items" :key="index" :label="item"
											   :value="item"/>
								</el-select>
							</td>
							<td>
								<el-input v-model="item.productName" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'"></el-input>
							</td>
							<td width="200">
								<el-input v-model="item.gradeValue" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'"></el-input>
							</td>
							<td>
								<el-input  @input="item.thNumber=item.thNumber.replace(/[^0-9\.]/g,'')" v-model="item.thNumber" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'" @change="totalNumChange(item)"></el-input>
							</td>
							<td>
								<el-input @input="item.peieceNum=item.peieceNum.replace(/[^\d]/g,'')" v-model="item.peieceNum" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'" @change="totalNumChange(item)"></el-input>
							</td>
							<td>
								<el-input v-model="item.totalNum" placeholder="" class="text_center" clearable
										  disabled></el-input>
							</td>
							<td>
								<el-input  @input="item.price=item.price.replace(/[^0-9\.]/g,'')" v-model="item.price" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'" @change="totalPriceChange(item)"></el-input>
							</td>
							<td>
								<el-input v-model="item.totalPrice" placeholder="" class="text_center" clearable
										  disabled></el-input>
							</td>
							<td>
								<el-input @input="item.goodsDay=item.goodsDay.replace(/[^\d]/g,'')" v-model="item.goodsDay" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'"></el-input>
							</td>
							<td>
								<el-input v-model="item.remark" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'"></el-input>
							</td>
							<td width="60">
								<span class="edit" @click.stop="deleteTable(item,index)">删除</span>
							</td>
						</tr>
					</table>
				</div>
			</el-form>
		</div>
	</div>
</template>
<script>
	import {getStore} from "@/plugins/localStore";
	import {formatDate} from "@/plugins/formatDate";

	export default {
		props: ['editData', 'type', 'selectItems'],
		data() {
			return {
				addForm: {
					id:'',
					orderNum:'',
					itemTypeId:'',
					productName:'',
					gradeValue:'',
					thNumber:'',
					peieceNum:'',
					totalNum:'',
					price:'',
					totalPrice:'',
					goodsDay:'',
					remark:'',
					createUserId:'',
					createUserName:'',
					orderType:'',
					customer:'',
					orderStatus:'',
				},
				rules: {

				},
				// customers: [],
				tableList:[],
				items: [],
				count: 0,
				user: {},
			}
		},
		methods: {

			totalNumChange(item){
				if(item.peieceNum && item.thNumber){
					let totalNum = parseFloat(item.peieceNum) *   parseFloat(item.thNumber);
					item.totalNum = totalNum.toFixed(4);
				}else{
					item.totalNum = '';
				}
			},

			querySearch(queryString,cb) {
				let self = this;
				let param = queryString;
				return new Promise((resolve, reject) => {
					self.$http({
						url: "/jinl/order/getNameByQuery",
						method: "post",
						data: JSON.stringify(param),
						dataType: 'json',
						contentType: "application/json",
					}).then(resp => {
						if (resp.success) {
							debugger
							const customers = resp.result.map(item => ({
								customer: item.customer,
								value: item.customer,
							}));
							cb(customers);
							resolve(customers); // 将处理后的客户数据传递给 resolve 函数
						} else {
							reject(); // 如果请求失败，可以调用 reject 函数处理错误
						}
					}).catch(error => {
						reject(error); // 如果请求发生错误，可以通过 reject 函数传递错误信息
					});
				});
			},
			totalPriceChange(item){
				if(item.totalNum && item.price){
					let totalPrice = parseFloat(item.price) *   parseFloat(item.totalNum) ;
					item.totalPrice = totalPrice.toFixed(2);
				}else{
					item.totalPrice = '';
				}
			},

			addTable(val) {
				if (this.tableList.length == 10) {
					this.$message.warning('最多添加10个订单');
					return;
				}
				if(val){
					this.tableList.push(val);
				}else{
					this.tableList.push(
						{
							checked: false,
							id:'',
							orderNum:'',
							itemTypeId:'',
							productName:'',
							gradeValue:'',
							thNumber:'',
							peieceNum:'',
							totalNum:'',
							price:'',
							totalPrice:'',
							goodsDay:'',
							remark:'',
							createUserId:this.user.id,
							createUserName:this.user.userName,
							orderType:'',
							customer:'',
							orderStatus:'',
						},
					);
				}

			},

			batchDelete() {
				let filter = this.tableList.filter((item) => !item.checked);
				this.tableList = JSON.parse(JSON.stringify(filter))
			},

			deleteTable(item, index) {//删除table
				this.tableList.splice(index, 1);
			},

			submitForm(val) {
				let self = this;
				self.$refs["addForm"].validate((valid) => {

					if (!self.addForm.customer) {
						self.$message.warning('请输入客户！');
						return;
					}
					if (!self.addForm.orderType) {
						self.$message.warning('请选择订单类型！');
						return;
					}

					if (valid) {
						if (self.tableList.length == 0) {
							self.$message.warning('请添加任务信息！');
							return;
						}

						let notValidator = ['id', 'orderNum', 'checked', 'remark', 'orderStatus','orderType','customer'];
						for (let row of self.tableList) {
							for (let key in row) {
								if (notValidator.includes(key)) {
									continue;
								}
								if (!row[key]) {
									console.log(key)
									self.$message.warning('有未填数据，请输入完整数据后提交！');
									return;
								}
							}
						}
						for (let data of self.tableList) {
							data.customer = self.addForm.customer;
							data.orderType = self.addForm.orderType;
							data.gradeValue = data.gradeValue.trim();
							let thNumber = parseFloat(data.thNumber);
							if (thNumber <= 0) {
								self.$message.warning('单件不能小于0！');
								return;
							}
							let peieceNum = parseFloat(data.peieceNum);
							if (peieceNum <= 0) {
								self.$message.warning('件数不能小于0！');
								return;
							}

							let price = parseFloat(data.price);
							if (price <= 0) {
								self.$message.warning('价格不能小于0！');
								return;
							}

							if (parseInt(data.goodsDay) <= 0) {
								self.$message.warning('交货期必须大于0！');
								return;
							}
						}
						self.operate(val);
					} else {
						return false;
					}
				});
			},

			operate() {
				let self = this;
				let params = {};
				if(self.addForm.id){
					params = JSON.parse(JSON.stringify(self.addForm));
				}else{
					params = JSON.parse(JSON.stringify(self.tableList));
				}
				let url = self.addForm.id ? '/jinl/order/updateOrder' : '/jinl/order/addBatchOrder';
				if (self.count == 0) {
					self.$http({
						url: url,
						method: "post",
						data: JSON.stringify(params),
						dataType: 'json',
						contentType: "application/json",
					}).then(resp => {
						if (resp.success) {
							self.$notify({title: '提示', message: "操作成功！", type: 'success'});
							self.count--;
							self.$eventBus.$emit("updateOrderList");
							self.$eventBus.$emit("getOrderNum");
							return;
						}
						self.$notify({title: '提示', message: resp.message, type: 'error'});
						self.count--;
					});
					self.count++;
				}
			},

		},

		watch: {
			selectItems(val) {
				this.items = val;
				console.log('---this.items----')
				console.log(this.items)
			},
			editData(val) {
				console.log(val)
				this.user = getStore();
				this.count = 0;
				for (let key in  this.addForm) {
					this.addForm[key] = val[key] || ''
				}
				if (this.type == 'add' && this.tableList.length == 0 ) {
					let self = this;
					self.$nextTick(() => {
						self.addTable();
					});
				}
			},

		},

		mounted() {

		},
		components: {}
	}
</script>
<style lang="scss" scoped>
	@import "@/style/dialog.scss";

	.business-workAdd.addProject {
		.tableList {
			margin-top: 0;

			table {
				table-layout: auto;

				tr {
					background: #fff !important;

					td {
						padding: 1px 3px;
					}

					&.noData {
						color: #999;
						height: 40px;
					}
				}

				.edit {
					color: #1890ff;
					padding: 0 5px;
					cursor: pointer;

					&.icons {
						font-size: 16px;
					}

					&:hover {
						opacity: .7;
					}
				}
			}
		}
	}
</style>